<template>
  <el-dialog
    :title="title"
    :visible.sync="open"
    width="620px"
    append-to-body
    @close="handleCancel"
    destroy-on-close
  >
    <hk-form
      ref="hkFormRef"
      :formLabels="formObj.formLabels"
      :rules="formObj.formRules"
      :data="formObj.formData"
      :dict-list="formObj.dictList"
      :label-width="formObj.labelWidth"
      :btn-hidden="formObj.btnHidden"
      :disabled="readonly"
      @handleEvent="handleEvent"
    >
      <template #filter-menuIds>
        <el-tree
          style="height: 25vh; overflow: auto"
          class="tree-border"
          :data="menuOptions"
          show-checkbox
          ref="menu"
          node-key="id"
          :check-strictly="false"
          empty-text="加载中，请稍候"
          :props="defaultProps"
          @check="handleCheckEvent"
        ></el-tree>
      </template>
    </hk-form>
    <div slot="footer" class="dialog-footer">
      <!-- <el-button type="primary" @click="handleSubmitEvent" v-if="formObj.formData.roleType != 1">确 定</el-button> -->
      <el-button type="primary" v-if="!readonly" @click="handleSubmitEvent">确 定</el-button>
      <el-button @click="handleCancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import HkForm from '@/components/HKForm'
import { addRole, getRole, updateRole } from '@/api/system/role'
import { nameRegx } from '@/utils/validate'
import { roleMenuTreeselect } from '@/api/system/menu'
import { treeselect as deptTreeselect, roleDeptTreeselect } from '@/api/system/dept'

export default {
  name: 'addDialog',
  components: { HkForm },
  props: {
    title: {
      type: String,
      default() {
        return '标题'
      }
    },
    statusDict: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      open: false,
      readonly: false,
      //  表单数据
      formObj: {
        btnHidden: true,
        labelWidth: '100',
        formLabels: [
          { label: '角色名称', field: 'name', type: 'input', span: 24,maxlength:50 },
          { label: '角色标识', field: 'code', type: 'input', span: 24,maxlength:50 },
          {
            label: '状态',
            field: 'status',
            type: 'radio',
            list: 'statusList',
            span: 24
          },
          {
            label: '菜单权限',
            field: 'menuIds',
            type: 'slot',
            span: 24
          }
        ],
        formRules: {
          name: [
            { required: true, message: '请输入角色名称', trigger: 'blur' },
            { pattern: nameRegx, message: '角色名称只能使用中文，英文字母和数字及下划线', trigger: 'blur' }
          ],
          code: [
            { required: true, message: '请输入角色标识', trigger: 'blur' },
            { pattern: nameRegx, message: '角色标识只能使用中文，英文字母和数字及下划线', trigger: 'blur' }
          ],
          status: [{ required: true, message: '请选择状态', trigger: 'blur' }]
          /*menuIds: [
            { required: true, message: '请选择菜单权限', trigger: 'blur' }
          ]*/
        },
        dictList: {
          statusList: []
        },
        formData: {
          id: undefined,
          name: undefined,
          code: undefined,
          status: undefined,
          menuIds: undefined
        }
      },
      menuOptions: this.menus,
      menuIds: null,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      id: ''
    }
  },
  methods: {
    show(id) {
      this.open = true
      this.getMenuTreeselect(id)
      if (id) {
        this.id = id
        this.loadData(id)
      } else {
        this.formObj.formData.status = '0'
      }
      this.formObj.dictList.statusList = this.statusDict.filter(i=>{
        return i.label=='正常'
      })
    },
    loadData(roleId) {
      getRole(roleId).then(response => {
        this.formObj.formData = response
        this.formObj.formData.status = response.status + ''
        this.readonly = response.roleType == 1
      })
    },
    /** 查询菜单树结构 */
    getMenuTreeselect(id) {
      id = id || 0
      roleMenuTreeselect(id).then(res => {
        let menuIds = res.checkedKeys
        this.formObj.formData.menuIds = menuIds
        this.menuOptions = res.menus
        if (menuIds) {
          menuIds.forEach(v => {
            this.$nextTick(() => {
              this.$refs.menu.setChecked(v, true, false)
            })
          })
        }
      })
    },
    /** 查询部门树结构 */
    getDeptTreeselect() {
      deptTreeselect().then(response => {
        this.deptOptions = response
      })
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.deptRef.getCheckedKeys()
      // 半选中的部门节点
      let halfCheckedKeys = this.$refs.deptRef.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    /** 根据角色ID查询菜单树结构 */
    getRoleMenuTreeselect(roleId) {
      return roleMenuTreeselect(roleId).then(response => {
        this.menuOptions = response.menus
        return response
      })
    },
    /** 根据角色ID查询部门树结构 */
    getRoleDeptTreeselect(roleId) {
      return roleDeptTreeselect(roleId).then(response => {
        this.deptOptions = response.orgs
        return response
      })
    },

    /**所有菜单节点数据  */
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys()
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    /**
     * 树节点被点击时触发事件
     * */
    handleCheckEvent(currentObj, allCheckedObj) {
      this.formObj.formData.menuIds = allCheckedObj.halfCheckedKeys.concat(allCheckedObj.checkedKeys)
    },

    /**
     * @funt 保存按钮
     * */
    async handleSubmitEvent(data) {
      this.formObj.formData.menuIds = this.getMenuAllCheckedKeys()
      let res = await this.$refs.hkFormRef.handleFormSubmit('formLabels')
      if (res && this.id) {
        updateRole(Object.assign(res, { id: this.id })).then(response => {
          this.$modal.msgSuccess('修改成功')
          this.handleCancel()
          this.$emit('submitForm', true)
        })
      } else if (res) {
        addRole(res).then(response => {
          this.$modal.msgSuccess('新增成功')
          this.handleCancel()
          this.$emit('submitForm', true)
        })
      }
    },

    handleCancel() {
      this.open = false
      this.readonly=false;
      this.id = null
      this.$refs.hkFormRef.resetForm('formLabels')
      this.$refs.menu.checkedKeys = []
      this.formObj.formData.menuIds = []
      this.formObj.formData = {}
    },
    /**
     * 表单变化事件
     * */
    handleEvent(data) {
      this.formObj.formData[data.field] = data.value
    }
  }
}
</script>

<style scoped></style>
